//
//  ClubInfoSearchListViewController.swift
//  77Club
//
//  Created by Apple on 2024/11/25.
//

import UIKit

class ClubInfoSearchListViewController: ClubBaseViewController {

    private let searchTextF = c_make_ex(UITextField.self)
        .corner(15).bgColor("#7B7D80".toColor.alpha(0.08))
        .color("#2E3033").font(12.font_medium)
        .placeholder("请输入关键进行搜索").end()
    private let cancelButton = c_make_ex(UIButton.self)
        .text("取消").color("#47494D").font(15.font_semiBold).end()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubInfoCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.rowHeight = 102.0.Scale
        return tableView
    }()
    private var emptyView = ClubEmptyArticleView()
    private var isSearch = false
    var updateHistoryData: (() -> Void)?
    
    var keyword: String = "" {
        didSet{
            loadData()
        }
    }
    
    private var sourceData: [ClubHomeInfoItemModel]?

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if isSearch {
            self.updateHistoryData?()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            searchTextF
            cancelButton
            tableView
            emptyView
        }
        
        searchTextF.leading(12.0.Scale).top(.statusHeight + 8.0.Scale).width(295.0.Scale).height(30)
        cancelButton.trailing(0).height(30)
        cancelButton.CenterY == searchTextF.CenterY
        cancelButton.Leading == searchTextF.Trailing
        tableView.trailing(0).leading(0).bottom(.safe_bottom).top(.navi_height + 6.0.Scale)
        emptyView.trailing(0).leading(0).top(.navi_height + 160.0.Scale).height(200)
        
        searchTextF.style { v in
            v.placehold("#AEB0B3".toColor, font: 12.font_medium)
            let leftV = UIView(frame: CGRect(x: 0, y: 0, width: 26, height: 30))
            let searchImg = UIImageView(frame: CGRect(x: 6, y: 7, width: 16, height: 16))
            searchImg.image = "Home_searchGray".toImage
            leftV.addSubview(searchImg)
            v.leftView = leftV
            v.leftViewMode = .always
            v.returnKeyType = .search
            v.delegate = self
        }
        emptyView.titleString = "暂无相关资讯~"
        emptyView.isHidden = true
        
        cancelButton.addTarget(self, action: #selector(clickDismissButton), for: .touchUpInside)
    }

    @objc private func clickDismissButton(){
        self.navigationController?.popViewController(animated: true)
    }
    
    private func loadData(){
        
        self.sourceData?.removeAll()
        Task{
            ToastUtil.show()
            let res = await network.requestSpecialData(.infolist(class_id: "", page: 1,keyword: self.keyword), type: ClubHomeInfoItemModel.self)
            ToastUtil.dismiss()
            if res.isSuccess, let models = res.models {
                self.sourceData = models
                self.tableView.reloadData()
            }
        }
    }

}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubInfoSearchListViewController: UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        self.emptyView.isHidden = !(sourceData?.count == 0)
        return sourceData?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubInfoCell", for: indexPath) as! ClubInfoCell
        cell.model = sourceData?[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let model = sourceData?[indexPath.row]
        let webView = ClubWebViewController()
        var urlStr = model?.webview_url ?? ""
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            urlStr = urlStr + "&uid=\(uid)"
        }
        urlStr = urlStr + "&model=ios"
        webView.urlString = urlStr
        webView.titleName = "资讯详情"
        webView.ishiddenNav = true
        self.navigationController?.pushViewController(webView, animated: true)
    }

    // 监听 return 键（即搜索按钮）被点击
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // 隐藏键盘
        textField.resignFirstResponder()
        // 执行搜索操作
        searchAction(text: textField.text)
        return true
    }
    
    // 搜索操作的逻辑
    func searchAction(text: String?) {
        if let searchText = text, !searchText.isEmpty {
            
            self.isSearch = true
            searchTextF.text = ""
            self.keyword = searchText
            if var history = UserDefaultsManager.getString(forKey: .searchInfoHistory), history.count > 0 {
                history.append("," + searchText)
                UserDefaultsManager.setString(history, forKey: .searchInfoHistory)
            }else{
                var tempArray = [String]()
                tempArray.append(searchText)
                let wordArray = tempArray.joined(separator: ",")
                UserDefaultsManager.setString(wordArray, forKey: .searchInfoHistory)
            }
        }
    }
}
